<template>
  <el-card class="mb-6 approval-flow-card" v-loading="loading">
    <template #header>
      <div class="card-header">
        <div class="header-left">
          <el-icon class="collapse-icon" :class="{ 'is-collapsed': !showApprovalFlow }" @click="toggleApprovalFlow">
            <ArrowDown />
          </el-icon>
          <span class="title">{{ title || '审核流程' }}</span>
        </div>
        <div class="header-right">
          <el-tag v-if="approvalInstance && approvalStages.length > 0" type="primary" size="large">
            共 {{ approvalInstance.stageCount || approvalStages.length }} 个阶段
          </el-tag>
          <el-tag v-else type="info" size="large">暂无审核流程</el-tag>
        </div>
      </div>
    </template>

    <transition name="slide-fade" mode="out-in">
      <div v-if="approvalInstance && approvalStages.length > 0 && showApprovalFlow" key="approval-flow" class="approval-flow-container">
        <!-- 审核流程基本信息 -->
        <div class="approval-info-section mb-6">
          <el-descriptions :column="3" border>
            <el-descriptions-item label="申请人">{{ approvalInstance.applicantName || '-' }}</el-descriptions-item>
            <el-descriptions-item label="提交时间">{{
              parseTime(approvalInstance.submitTime, '{y}-{m}-{d} {h}:{i}:{s}') || '-'
            }}</el-descriptions-item>
            <el-descriptions-item label="当前阶段">第{{ approvalInstance.approvalCurrentStage || 0 }}阶段</el-descriptions-item>
            <el-descriptions-item label="审核状态">
              <dict-tag :options="approval_commit_status" :value="approvalInstance.approvalStatus || ''" />
            </el-descriptions-item>
            <el-descriptions-item label="总阶段数">{{ approvalInstance.stageCount || 0 }}个阶段</el-descriptions-item>
            <el-descriptions-item label="完成时间">
              {{ approvalInstance.finishTime ? parseTime(approvalInstance.finishTime, '{y}-{m}-{d} {h}:{i}:{s}') : '-' }}
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 审核流程步骤 -->
        <el-steps :active="getCurrentStepIndex()" align-center class="mb-6">
          <el-step
            v-for="stage in approvalStages"
            :key="stage.id"
            :title="stage.stageName"
            :description="getStageDescription(stage)"
            :status="getStageStatus(stage)"
            :icon="getStageIcon(stage)"
          />
        </el-steps>

        <!-- 详细审核信息 -->
        <div class="approval-details">
          <el-collapse v-model="expandedStages" class="stage-collapse">
            <el-collapse-item
              v-for="stage in approvalStages"
              :key="stage.id"
              :name="stage.id"
              class="stage-collapse-item"
              :class="{ 'current-stage': stage.isCurrent }"
            >
              <template #title>
                <div class="stage-header-compact">
                  <div class="stage-info-compact">
                    <span class="stage-number-compact">第{{ stage.stageSort }}阶段</span>
                    <span class="stage-name-compact">{{ stage.stageName }}</span>
                    <dict-tag :options="approval_commit_status" :value="stage.approvalStatus" class="ml-2" />
                    <el-tag v-if="stage.isCurrent" type="warning" size="small" class="ml-1">当前阶段</el-tag>
                    <span v-if="stage.approvalRecords && stage.approvalRecords.length > 0" class="approver-count">
                      ({{ stage.approvalRecords.length }}人)
                    </span>
                  </div>
                </div>
              </template>

              <!-- 阶段描述 -->
              <div v-if="stage.stageDescription" class="stage-desc-expanded">
                {{ stage.stageDescription }}
              </div>

              <!-- 审核人员列表 -->
              <div v-if="stage.approvalRecords && stage.approvalRecords.length > 0" class="approvers-list-compact">
                <div class="approver-cards-compact">
                  <el-tooltip
                    v-for="record in stage.approvalRecords"
                    :key="record.id"
                    :content="getTooltipContent(record)"
                    placement="top"
                    :disabled="!getTooltipContent(record)"
                    raw-content
                  >
                    <div class="approver-card-compact" :class="getApproverCardClass(record.approvalResult)">
                      <div class="approver-avatar">
                        <el-icon class="approver-icon-compact">
                          <User />
                        </el-icon>
                      </div>
                      <div class="approver-info-compact">
                        <div class="approver-name-compact">
                          {{ record.approverName || `审核人${record.approverId}` }}
                        </div>
                        <div class="approver-status-compact">
                          <dict-tag :options="approval_record_status" :value="record.approvalResult" size="small" />
                        </div>
                        <div v-if="record.approvalTime" class="approval-time-compact">
                          {{ parseTime(record.approvalTime, '{m}-{d} {h}:{i}') }}
                        </div>
                      </div>
                    </div>
                  </el-tooltip>
                </div>
              </div>
              <div v-else class="no-approvers-compact">
                <el-empty description="暂未配置审核人员" :image-size="40" />
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
      </div>
      <div v-else-if="showApprovalFlow && (!approvalInstance || approvalStages.length === 0)" key="no-flow" class="no-approval-flow">
        <el-empty description="该项目暂未配置审核流程" :image-size="100" />
      </div>
    </transition>
  </el-card>
</template>

<script setup lang="ts">
import { parseTime } from '@/utils/ruoyi';
import { displayApprovalFlow } from '@/api/other/approval/index';
import { Check, Close, User, ArrowDown } from '@element-plus/icons-vue';

// 定义组件属性
interface Props {
  businessType?: string; // 业务类型
  businessId?: string | number; // 业务ID
  title?: string; // 标题
  autoLoad?: boolean; // 是否自动加载数据
  showCollapse?: boolean; // 是否显示折叠功能
}

const props = withDefaults(defineProps<Props>(), {
  businessType: 'PROJECT-SPLIT-FLOW',
  businessId: '',
  title: '审核流程',
  autoLoad: true,
  showCollapse: true
});

// 定义事件
const emit = defineEmits<{
  'update:loading': [value: boolean];
  'data-loaded': [data: any[]];
  'error': [error: any];
}>();

const { proxy } = getCurrentInstance();
const { approval_commit_status, approval_record_status } = toRefs<any>(proxy?.useDict('approval_commit_status', 'approval_record_status'));

// 数据状态
const loading = ref(false);
const approvalStages = ref<any[]>([]);
const expandedStages = ref<any[]>([]);
const showApprovalFlow = ref(false);
const approvalInstance = ref<any>(null);

/**
 * 获取审核阶段信息
 */
const getApprovalStagesInfo = async () => {
  if (!props.businessId) {
    console.warn('业务ID不能为空');
    return;
  }

  try {
    loading.value = true;
    emit('update:loading', true);

    const res = await displayApprovalFlow(props.businessType, props.businessId.toString());
    const data = res.data;

    if (data) {
      // 保存审核实例信息
      approvalInstance.value = data;

      // 处理审核阶段数据
      approvalStages.value = (data.approvalStageVos || []).map((stage: any) => ({
        ...stage,
        isCurrent: stage.stageSort === data.approvalCurrentStage
      }));

      // 无论组件是否展开，都保持所有阶段收起状态
      // 用户需要手动点击才能展开各个阶段
      expandedStages.value = [];
    } else {
      approvalStages.value = [];
      approvalInstance.value = null;
    }

    emit('data-loaded', approvalStages.value);
  } catch (error) {
    console.error('获取审核阶段信息失败:', error);
    emit('error', error);
    // 不显示错误信息，因为可能还没有配置审核流程
  } finally {
    loading.value = false;
    emit('update:loading', false);
  }
};

/**
 * 获取当前步骤索引
 */
const getCurrentStepIndex = () => {
  if (approvalInstance.value) {
    return approvalInstance.value.approvalCurrentStage - 1;
  }
  const currentStage = approvalStages.value.find((stage) => stage.isCurrent);
  return currentStage ? currentStage.stageSort - 1 : approvalStages.value.length;
};

/**
 * 获取阶段描述
 */
const getStageDescription = (stage: any) => {
  // 使用字典获取状态文本
  const statusOption = approval_commit_status.value?.find((option) => option.value === stage.approvalStatus);
  const statusText = statusOption?.label || '未知状态';
  return stage.stageDescription ? `${stage.stageDescription} (${statusText})` : statusText;
};

/**
 * 获取阶段状态
 */
const getStageStatus = (stage: any) => {
  const status = stage.approvalStatus;
  switch (status) {
    case '3':
      return 'finish'; // 审核通过
    case '4':
      return 'error'; // 审核不通过
    case '2':
      return 'process'; // 审核中
    case '1':
      return 'wait'; // 已提交
    default:
      return 'wait'; // 默认等待
  }
};

/**
 * 获取阶段图标
 */
const getStageIcon = (stage: any) => {
  const status = stage.approvalStatus;
  switch (status) {
    case '3':
      return Check;
    case '4':
      return Close;
    default:
      return undefined;
  }
};

/**
 * 获取审核人卡片样式类
 */
const getApproverCardClass = (result: string) => {
  switch (result) {
    case '1':
      return 'approved';
    case '2':
      return 'rejected';
    default:
      return 'waiting';
  }
};

/**
 * 获取tooltip内容
 */
const getTooltipContent = (record: any) => {
  if (!record.approvalOpinion) return '';

  let content = `<div style="max-width: 300px;">
    <div style="font-weight: bold; margin-bottom: 8px;">${record.approverName || `审核人${record.approverId}`}</div>`;

  if (record.approvalTime) {
    content += `<div style="color: #909399; font-size: 12px; margin-bottom: 8px;">
      ${parseTime(record.approvalTime, '{y}-{m}-{d} {h}:{i}')}
    </div>`;
  }

  content += `<div style="line-height: 1.6; margin-top: 8px;">
  <div style="color: #606266; font-weight: 500; margin-bottom: 4px; font-size: 12px;">
    审核意见：
    <span style="color: #909399; font-weight: normal;">${record.approvalOpinion}</span>
  </div>
</div>`;

  return content;
};

/**
 * 切换审核流程显示状态（优化版本：收起时先内部收起再整体收起，展开时平滑动画）
 */
const toggleApprovalFlow = async () => {
  if (!props.showCollapse) return;

  if (showApprovalFlow.value) {
    // 收起时，先收起所有内部阶段
    expandedStages.value = [];
    await nextTick(); // 等 DOM 更新，内部折叠开始动画

    // 等待内部阶段收起完成，然后直接收起整体（不使用动画）
    setTimeout(() => {
      showApprovalFlow.value = false;
    }, 300); // 300ms = 内部折叠动画时间
  } else {
    // 展开时直接展开，保持流畅的下拉动画
    showApprovalFlow.value = true;

    // 展开后所有阶段都保持收起状态，用户需要手动点击展开
    await nextTick();
    expandedStages.value = [];
  }
};

// 监听业务ID变化，重新加载数据
watch(
  () => props.businessId,
  (newVal) => {
    if (newVal && props.autoLoad) {
      getApprovalStagesInfo();
    }
  },
  { immediate: false }
);

// 暴露方法给父组件
defineExpose({
  getApprovalStagesInfo,
  approvalStages,
  expandedStages,
  showApprovalFlow,
  approvalInstance
});

onMounted(() => {
  if (props.autoLoad && props.businessId) {
    getApprovalStagesInfo();
  }
});
</script>

<style lang="scss" scoped>
.approval-flow-card {
  margin-bottom: 20px;
  border-radius: 12px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .header-left {
    display: flex;
    align-items: center;
    gap: 8px;

    .collapse-icon {
      cursor: pointer;
      color: #409eff;
      font-size: 16px;
      transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);

      &:hover {
        color: #66b1ff;
      }

      &.is-collapsed {
        transform: rotate(-90deg);
      }
    }

    .title {
      font-size: 16px;
      font-weight: bold;
    }
  }

  .header-right {
    display: flex;
    align-items: center;
  }
}

/* 折叠面板样式 */
.stage-collapse {
  border: none;

  :deep(.el-collapse-item) {
    margin-bottom: 16px;
    border-radius: 8px;
    border: 1px solid #e4e7ed;
    overflow: hidden;
    transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);

    &.current-stage {
      border-color: #409eff;
      box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
    }

    .el-collapse-item__header {
      background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
      border: none;
      padding: 16px 20px;
      font-weight: 500;
      transition: background 0.2s ease;

      &:hover {
        background: linear-gradient(135deg, #e9ecef 0%, #dee2e6 100%);
      }

      .el-collapse-item__arrow {
        color: #409eff;
        font-weight: bold;
        transition: transform 0.2s cubic-bezier(0.4, 0, 0.2, 1);
      }
    }

    .el-collapse-item__wrap {
      border: none;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

      .el-collapse-item__content {
        padding: 0 20px 20px;
        background: #fff;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      }
    }
  }
}

/* 紧凑型阶段标题 */
.stage-header-compact {
  width: 100%;

  .stage-info-compact {
    display: flex;
    align-items: center;
    gap: 12px;

    .stage-number-compact {
      font-weight: 600;
      color: #409eff;
      font-size: 14px;
    }

    .stage-name-compact {
      font-weight: 500;
      color: #303133;
      font-size: 14px;
    }

    .approver-count {
      color: #909399;
      font-size: 12px;
      font-weight: normal;
    }
  }
}

/* 展开后的阶段描述 */
.stage-desc-expanded {
  background: #f5f7fa;
  padding: 12px 16px;
  border-radius: 6px;
  color: #606266;
  font-size: 13px;
  line-height: 1.5;
  margin-top: 16px;
  margin-bottom: 16px;
  border-left: 3px solid #409eff;
}

/* 紧凑型审核人员列表 */
.approvers-list-compact {
  .approver-cards-compact {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
    gap: 10px;

    .approver-card-compact {
      background: #fff;
      border: 1px solid #e4e7ed;
      border-radius: 6px;
      padding: 10px;
      transition: all 0.3s ease;
      cursor: pointer;
      position: relative;

      &:hover {
        border-color: #409eff;
        box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15);
        transform: translateY(-2px);
      }

      &.approved {
        border-color: #67c23a;
        background: linear-gradient(135deg, #f0f9ff 0%, #e6f7ff 100%);

        &:hover {
          border-color: #67c23a;
          box-shadow: 0 2px 8px rgba(103, 194, 58, 0.2);
        }
      }

      &.rejected {
        border-color: #f56c6c;
        background: linear-gradient(135deg, #fef0f0 0%, #fde2e2 100%);

        &:hover {
          border-color: #f56c6c;
          box-shadow: 0 2px 8px rgba(245, 108, 108, 0.2);
        }
      }

      &.waiting {
        border-color: #e6a23c;
        background: linear-gradient(135deg, #fdf6ec 0%, #faecd8 100%);

        &:hover {
          border-color: #e6a23c;
          box-shadow: 0 2px 8px rgba(230, 162, 60, 0.2);
        }
      }

      .approver-avatar {
        display: flex;
        justify-content: center;
        margin-bottom: 6px;

        .approver-icon-compact {
          width: 28px;
          height: 28px;
          background: #409eff;
          color: white;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 14px;
        }
      }

      .approver-info-compact {
        text-align: center;

        .approver-name-compact {
          font-weight: 500;
          color: #303133;
          font-size: 12px;
          margin-bottom: 4px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        .approver-status-compact {
          margin-bottom: 3px;

          :deep(.el-tag) {
            font-size: 10px;
            height: 18px;
            line-height: 16px;
            padding: 0 6px;
          }
        }

        .approval-time-compact {
          color: #909399;
          font-size: 10px;
          line-height: 1.2;
        }
      }
    }
  }
}

/* 无审核人员状态 */
.no-approvers-compact {
  text-align: center;
  padding: 20px;
  color: #909399;
}

.no-approval-flow {
  text-align: center;
  padding: 40px;
}

/* 审核流程样式 */
.approval-flow-container {
  margin-top: 20px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  will-change: transform, opacity;
}

/* 审核信息区域样式 */
.approval-info-section {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-radius: 8px;
  padding: 16px;
  border: 1px solid #e4e7ed;

  :deep(.el-descriptions) {
    .el-descriptions__header {
      margin-bottom: 12px;
    }

    .el-descriptions__body {
      .el-descriptions__table {
        .el-descriptions__cell {
          padding: 12px 16px;
          font-size: 14px;

          &.el-descriptions__label {
            background-color: #f5f7fa;
            font-weight: 600;
            color: #2c3e50;
          }

          &.el-descriptions__content {
            background-color: #fff;
            color: #606266;
          }
        }
      }
    }
  }
}

.approval-details {
  margin-top: 30px;
}

/* 折叠展开动画 */
.slide-fade-enter-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  overflow: hidden;
}

.slide-fade-leave-active {
  /* 收起时直接隐藏，不使用动画 */
  transition: none;
  overflow: hidden;
}

.slide-fade-enter-from {
  opacity: 0;
  transform: translateY(-8px);
  max-height: 0;
}

.slide-fade-leave-to {
  opacity: 0;
  transform: translateY(0);
  max-height: 0;
}

.mb-6 {
  margin-bottom: 24px;
}

.ml-1 {
  margin-left: 4px;
}

.ml-2 {
  margin-left: 8px;
}
</style>
